package com.cw.jeeyt.service.impl.system;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.stereotype.Service;

import com.cw.jeeyt.service.intf.system.VelocityService;
import com.cw.lang.common.log.Log;
import com.cw.lang.common.log.TenantLog;

/**
 * velocity相关接口实现类
 *
 * @author: chenw
 * @create: 2018-12-20 11:41
 */
@Service
public class VelocityServiceImpl implements VelocityService {

    private static final String DEF_ENCODING = "utf-8";
    private Log logger = TenantLog.getLogger(VelocityServiceImpl.class);

    /**
     * 生成文件
     */
    @Override
    public void generateFile(String outputPath, String templatePath, VelocityContext context) throws Exception {
        BufferedWriter writer = null;
        try {
            Properties properties = new Properties();
            try {
                properties.load(this.getClass()
                    .getResourceAsStream("/velocity.properties"));
            } catch (IOException e) {
                logger.error("can't load configuration from velocity.properties", e);
                return;
            }
            Velocity.init(properties);
            Template template = getVelocityTemplate(templatePath);
            writer = getWriterStream(outputPath);
            template.merge(context, writer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取Velocity模板
     *
     * @param templatePath
     * @author chenw
     */
    public Template getVelocityTemplate(String templatePath) throws Exception {
        Template template = new Template();
        try {
            template = Velocity.getTemplate(templatePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return template;
    }

    /**
     * 获取Velocity写入流
     *
     * @author chenw
     */
    private BufferedWriter getWriterStream(String outputFile) throws Exception {
        try {
            File file = new File(outputFile);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, DEF_ENCODING));
            return writer;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
